/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.acake.dataclass;

import org.pleasantnightmare.acake.errorhandling.CheckError;
import org.pleasantnightmare.acake.errorhandling.DefaultErrorHandler;
import org.pleasantnightmare.acake.errorhandling.ErrorHandler;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.Set;

import static org.pleasantnightmare.acake.dataclass.DataCheckErrors.*;

/**
 * Processes Data annotation
 *
 * @author deus
 * @version 1.0
 * @see Data
 * @since Nov 16, 2009 7:54:06 AM
 */
@SupportedAnnotationTypes("Data")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class DataProcessor extends AbstractProcessor {
    private Class<?> clazz;
    private BeanInfo beanInfo;
    private ErrorHandler errorHandler;

    public void setErrorHandler(ErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Override
    public void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        errorHandler = new DefaultErrorHandler(processingEnv.getMessager());
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        // This should give us all classes annotated with @Data - we know this up front because @Data
        // is ONLY for classes
        Set<TypeElement> elements = (Set<TypeElement>) roundEnv.getElementsAnnotatedWith(annotations.iterator().next());

        for (TypeElement clazzElement : elements) {
            try {
                // Query type for data needed for checks
                clazz = Class.forName(clazzElement.getQualifiedName().toString());
                beanInfo = Introspector.getBeanInfo(clazz);
                checkAll();
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e);
            } catch (IntrospectionException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }

    void testMethodSetClazz(Class<?> clazz) {
        this.clazz = clazz;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
    }

    private void report(CheckError checkError, Object... args) {
        checkError.setMessageParams(args);
        errorHandler.report(checkError);
    }

    public void checkAll() {
        checkEmptyConstructor();
        checkFullArgConstructor();
        checkRWProperties();
        checkNoAdditionalMemberMethods();
        checkEquals();
        checkHashcode();
        checkToString();
        checkDependencies();
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "@Data checks performed on class: " + clazz.getName());
    }

    public void checkEmptyConstructor() {
        Constructor<?>[] constructors = clazz.getConstructors();
        // No public constructors
        if (constructors.length == 0) {
            report(NO_EMPTY_CONSTRUCTOR);
            return;
        }

        // Search for public no-arg constructor
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length == 0)
                return;
        }

        // If we're here, there is no public empty constructor
        report(NO_EMPTY_CONSTRUCTOR);
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "Empty constructor check done.");
    }

    public void checkFullArgConstructor() {
        Constructor<?>[] constructors = clazz.getConstructors();

        // No public constructors
        if (constructors.length == 0) {
            report(NO_FULL_ARG_CONSTRUCTOR);
            return;
        }

        // Search for public no-arg constructor
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length == clazz.getDeclaredFields().length)
                return;
        }

        // If we're here, there is no public full arg constructor
        report(NO_FULL_ARG_CONSTRUCTOR);
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "Full-arg constructor check done.");
    }

    public void checkRWProperties() {
        Field[] fields = clazz.getDeclaredFields();
        PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors();
        // -1 because getClass is counted as bean property
        int classPropertyCount = pd.length - 1;

        if (fields.length > classPropertyCount)
            report(MISSING_BEAN_PROPERTY_METHOD, fields.length, classPropertyCount);

        for (PropertyDescriptor propertyDescriptor : pd) {
            // Skip class property
            if ("class".equals(propertyDescriptor.getName()))
                continue;
            // Skip check from Identified interface from reflection-dao project
            if ("alreadyIdentified".equals(propertyDescriptor.getName()))
                continue;


            if (propertyDescriptor.getReadMethod() == null)
                report(NO_READABLE_PROPERTY_METHOD, propertyDescriptor.getName());
            if (propertyDescriptor.getWriteMethod() == null)
                report(NO_WRITEABLE_PROPERTY_METHOD, propertyDescriptor.getName());
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "ReadWrite properties check done.");
    }

    public void checkNoAdditionalMemberMethods() {
        Method[] allMethods = clazz.getDeclaredMethods();

        for (Method method : allMethods) {
            String methodName = method.getName();

            // First check on the name
            if (methodName.equals("equals")
                    || methodName.equals("hashCode")
                    || methodName.equals("toString")
                    || isPartOfRWProperty(methodName))
                continue;

            // Allow for static methods
            if ((method.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
                continue;

            report(EXTRA_METHOD, methodName);
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "Additional member methods check done.");
    }

    private boolean isPartOfRWProperty(String methodName) {
        PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : pd) {
            if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
                if (methodName.equals(propertyDescriptor.getReadMethod().getName())
                        || methodName.equals(propertyDescriptor.getWriteMethod().getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public void checkEquals() {
        try {
            clazz.getDeclaredMethod("equals", Object.class);
        } catch (NoSuchMethodException e) {
            report(NO_EQUALS);
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "Equals check done.");
    }

    public void checkHashcode() {
        try {
            clazz.getDeclaredMethod("hashCode");
        } catch (NoSuchMethodException e) {
            report(NO_HASHCODE);
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "HashCode check done.");
    }

    public void checkToString() {
        try {
            clazz.getDeclaredMethod("toString");
        } catch (NoSuchMethodException e) {
            report(NO_TOSTRING);
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "ToString check done.");
    }

    public void checkDependencies() {
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            Class<?> type = field.getType();
            // Check all primitives first
            if (Byte.class.equals(type)
                    || Character.class.equals(type)
                    || Boolean.class.equals(type)
                    || Short.class.equals(type)
                    || Integer.class.equals(type)
                    || Long.class.equals(type)
                    || Float.class.equals(type)
                    || Double.class.equals(type)
                    || String.class.equals(type)
                    || Date.class.equals(type)
                    || java.sql.Date.class.equals(type))
                continue;

            // If its not a primitive, it has to be another @Data class
            Annotation[] declAnnot = type.getDeclaredAnnotations();
            boolean foundDataAnnotation = false;
            for (Annotation annotation : declAnnot)
                if (Data.class.equals(annotation.annotationType())) {
                    foundDataAnnotation = true;
                    break;
                }

            if (!foundDataAnnotation)
                report(DEPENDENCY_NOT_PRIMITIVE_OR_DATA, field.getName());
        }
        errorHandler.printMessage(Diagnostic.Kind.NOTE, "Dependencies check done.");
    }
}
